package ex2;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;


public class Client extends JFrame{

	private JTextField input;
	private JTextArea display;
	private RequestButton button;
	private Socket client;
	private String request;
	private static int counter = 0;
	private int id;
	
	public Client(){
		super("Client");
		id = ++counter;
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(300, 200);
		setLayout(new BorderLayout());
		display = new JTextArea();
		display.setEditable(false);
		display.setLineWrap(true);
		input = new JTextField(10);
		button = new RequestButton(this);
		JPanel bottom = new JPanel();
		bottom.setLayout(new FlowLayout());
		bottom.add(input);
		bottom.add(button);
		getContentPane().add(display,BorderLayout.NORTH);
		getContentPane().add(bottom,BorderLayout.SOUTH);
		setVisible(true);
	}

	public void getRequest(){
		try{
			client = new Socket("127.0.0.1", 4242);
			PrintWriter out = new PrintWriter(client.getOutputStream(), true);
			request = input.getText();
			System.out.println("Client " + id + ">" + request);
			Thread.sleep(100);
			out.println(request);
			BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
			String answer = in.readLine();
			System.out.println("Client " + id + ">" + answer);
			display.append(answer);
			in.close();
			out.close();
			client.close();
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public JTextArea getDisplay(){
		return display;
	}
	
	public class RequestButton extends JButton{
		
		private Client client;
		
		public RequestButton(Client client){
			super("Request");
			this.client = client;
			addMouseListener(new MouseListener(){
				public void mouseReleased(MouseEvent e){
					
				}
				
				public void mouseClicked(MouseEvent e){
					getRequest();
				}
				
				public void mousePressed(MouseEvent e){
					
				}
				
				public void mouseEntered(MouseEvent e){
					
				}
				
				public void mouseExited(MouseEvent e){
					
				}
			});
		}
		
		public void getRequest(){
			client.getRequest();
		}
	}
	
	public static void main(String[] args){
		Client client = new Client();
	}
}
